import send from '@/config/MailConfig'
import bcrypt from 'bcryptjs'
import moment from 'moment'
import jsonwebtoken from 'jsonwebtoken'
import config from '@/config'
import { checkCode, generateToken } from '@/common/Utils'
import User from '@/model/User'
import SignRecord from '../model/SignRecord'
import { v4 as uuid } from 'uuid'
import { setValue, getValue, delValue } from '@/config/RedisConfig'
import jwt from 'jsonwebtoken'
import { getJWTPayload } from '@/common/Utils'
import { wxgetUserinfo } from '@/common/WxUtils'

class LoginController {
  constructor() {}
  async forget(ctx) {
    //忘记密码
    const { body } = ctx.request
    console.log(body)
    let sid = body.sid
    let code = body.code
    // 验证图片验证码的时效性、正确性
    let result = await checkCode(sid, code)
    if (!result) {
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确,请检查!',
      }
      return
    } else {
      try {
        // body.username -> database -> email
        let ischeck = false
        const user = await User.findOne({ username: body.username })
        let msg = ''
        if (body.username === user.username) {
          ischeck = true
        }
        if (ischeck) {
          const key = uuid()
          setValue(
            key,
            jwt.sign({ _id: user._id }, config.JWT_SECRET, {
              expiresIn: '30m',
            })
          )
          let result = await send({
            type: 'reset',
            data: {
              key: key,
              username: body.username,
            },
            code: '',
            expire: moment().add(30, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
            email: user.username,
            user: user.name,
          })
          msg = '更新密码需要进行邮件点击链接重置，注意查收邮件'
          ctx.body = {
            code: 200,
            msg: msg,
          }
        }
        const arr = ['password', 'mobile', 'username']
        arr.map((item) => {
          delete body[item]
        })
      } catch (e) {
        ctx.body = {
          code: 500,
          msg: '请检查用户名,邮件发送失败',
        }
      }
    }
  }
  async reset(ctx) {
    //重置密码
    const { body } = ctx.request
    console.log(body)
    let result = await checkCode(body.sid, body.code)
    if (!result) {
      ctx.body = {
        code: 500,
        msg: '验证码错误,请重新输入',
      }
      return
    } else {
      //校验验证码
      //取redis的sid后将token 转_id 后更新数据库
      // const obj = getHValue(body.sid)
      const Token = await getValue(body.token)
      let obj = await getJWTPayload('Bearer ' + Token)
      // console.log(obj)
      // if (obj !== 'undefined' && obj.meessage !== 'undefined') {
      //   return (ctx.body = {
      //     code: 404,
      //     msg: '邮件生效时间已过，无法正常修改密码，请重新发送邮件。',
      //   })
      // }
      if (obj !== 'undefined') {
        //邮件点击后的确认修改
        if (body.password === body.repassword) {
          //通过_id改数据库
          //转加密
          // const repassword = bcrypt.
          body.repassword = await bcrypt.hash(body.repassword, 5)
          const user = await User.updateOne(
            { _id: obj._id },
            { $set: { password: body.repassword } }
          )
          if (user.matchedCount === 1) {
            ctx.body = {
              code: 200,
              msg: '更改密码成功',
            }
            //重置删除token
            const Token2 = await delValue(body.token)
          }
        }
      } else {
        ctx.body = {
          code: 400,
          msg: '邮件已经过期请重新获取',
        }
      }
    }
  }

  async login(ctx) {
    // 接收用户的数据
    // 返回token
    // const body = ctx.request.query
    // const { body } = ctx.request

    // let Body = JSON.parse(body)
    // console.log(Body);
    // const sid = Body.sid
    // const code = Body.code
    const { body } = ctx.request
    let sid = body.sid
    let code = body.code
    // 验证图片验证码的时效性、正确性
    let result = await checkCode(sid, code)
    if (result) {
      // 验证用户账号密码是否正确
      let checkUserPasswd = false
      let user = await User.findOne({ username: body.username })
      if (await bcrypt.compare(body.password, user.password)) {
        // if (user.password=== body.password) {
        checkUserPasswd = true
      }
      // mongoDB查库
      if (checkUserPasswd) {
        // 验证通过，返回Token数据
        // console.log('Hello login')
        const userObj = user.toJSON() //mongose取到...user的doc
        const arr = ['password', 'username']
        arr.map((item) => {
          delete userObj[item]
        })
        let token = jsonwebtoken.sign({ _id: userObj._id }, config.JWT_SECRET, {
          expiresIn: '1d',
        })
        //登录判断issign
        const signRecord = await SignRecord.findByUid(userObj._id)
        if (signRecord !== null) {
          if (
            moment(signRecord.created).format('YYYY-MM-DD') ===
            moment().format('YYYY-MM-DD')
          ) {
            userObj.isSign = true
          } else {
            userObj.isSign = false
          }
          //有数据签到数据存储lastSign
          userObj.lastSign = signRecord.created
        } else {
          userObj.isSign = false
        }
        ctx.body = {
          code: 200,
          token: token,
          data: userObj,
        }
      } else {
        // 用户名 密码验证失败，返回提示
        ctx.body = {
          code: 404,
          msg: '用户名或者密码错误',
        }
      }
    } else {
      // 图片验证码校验失败
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确,请检查!',
      }
    }
  }

  async reg(ctx) {
    // 接收客户端的数据
    console.log(ctx.request)
    const { body } = ctx.request
    // console.log(body);
    // 校验验证码的内容（时效性、有效性）
    let sid = body.sid
    let code = body.code
    let msg = {}
    // 验证图片验证码的时效性、正确性
    let result = await checkCode(sid, code)
    let check = true
    if (result) {
      // 查库，看username是否被注册
      let user1 = await User.findOne({ username: body.username })
      if (user1 !== null && typeof user1.username !== 'undefined') {
        msg.username = ['此邮箱已经注册，可以通过邮箱找回密码']
        check = false
      }
      let user2 = await User.findOne({ name: body.name })
      // 查库，看name是否被注册
      if (user2 !== null && typeof user2.name !== 'undefined') {
        msg.name = ['此昵称已经被注册，请修改']
        check = false
      }
      // 写入数据到数据库
      if (check) {
        body.password = await bcrypt.hash(body.password, 5)
        // body.password = await (body.password)
        let user = new User({
          name: body.name,
          username: body.username,
          name: body.name,
          password: body.password,
          created: moment().format('YYYY-MM-DD HH:mm:ss'),
        })
        let result = await user.save()
        ctx.body = {
          code: 200,
          data: result,
          msg: '注册成功',
        }
        return
      }
    } else {
      // veevalidate 显示的错误
      msg.code = ['验证码已经失效，请重新获取!']
    }
    ctx.body = {
      code: 500,
      msg: msg,
    }
  }
  async alogin(ctx) {
    // 接收用户的数据
    // 返回token
    const { body } = ctx.request
    console.log(body)
    let sid = body.sid
    let code = body.code
    // 验证图片验证码的时效性、正确性
    let result = await checkCode(sid, code)
    if (result) {
      // 验证用户账号密码是否正确
      let checkUserPasswd = false
      let user = await User.findOne({ username: body.username })
      if (user === null || user === 'undefined') {
        ctx.body = {
          code: 404,
          msg: '用户名或者密码错误',
        }
        return
      }
      if (await bcrypt.compare(body.password, user.password)) {
        let role = false
        if (user.roles[0] === 'admin') {
          checkUserPasswd = true
        } else {
          return (ctx.body = {
            code: 404,
            msg: '该用户非管理员禁止登陆',
          })
        }
      }
      // mongoDB查库
      if (checkUserPasswd) {
        // 验证通过，返回Token数据
        // console.log('Hello login')
        const userObj = user.toJSON() //mongose取到...user的doc
        console.log(userObj)
        const arr = ['password', 'username', 'roles']
        arr.map((item) => {
          delete userObj[item]
        })
        let token = jsonwebtoken.sign({ _id: userObj._id }, config.JWT_SECRET, {
          expiresIn: '1d',
        })
        ctx.body = {
          code: 200,
          token: token,
          data: userObj,
        }
      } else {
        // 用户名 密码验证失败，返回提示
        ctx.body = {
          code: 404,
          msg: '用户名或者密码错误',
        }
      }
    } else {
      // 图片验证码校验失败
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确,请检查!',
      }
    }
  }
  async wxlogin(ctx) {
    //接受用户传递的code
    const { body } = ctx.request
    let user
    if (body.code) {
      const wxuserInfo = await wxgetUserinfo(body.user, body.code)
      if (wxuserInfo.errcode === 0) {
        user = await User.findorcreatedByOpenData(wxuserInfo)
        ctx.body = {
          code: 200,
          data: user,
          token: generateToken({ _id: user._id }),
          msg: '登录成功',
        }
      } else {
        ctx.throw({
          code: wxuserInfo.errcode || 501,
          message: wxuserInfo.errmsg,
        })
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '没有足够的参数',
      }
    }
  }
}

export default new LoginController()
